package TP;

import fr.inria.acacia.corese.api.IDatatype;
import fr.inria.acacia.corese.exceptions.EngineException;
import fr.inria.edelweiss.kgram.core.Mapping;
import fr.inria.edelweiss.kgram.core.Mappings;
import fr.inria.edelweiss.kgraph.core.Graph;
import fr.inria.edelweiss.kgraph.query.QueryProcess;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 *
 * @author userepu
 */
@WebServlet(name = "artisteServlet", urlPatterns = {"/artisteServlet"})
public class artisteServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, EngineException, URISyntaxException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {

//        String dbpedia_service = "<http://dbpedia.org/sparql>";
            ServletContext context = getServletConfig().getServletContext();
            Graph graph = Server.getGraph(context);
            String artiste = request.getParameter("artisteCherche");
            QueryProcess exec = QueryProcess.create(graph);
            String query = "prefix geo: <http://www.w3.org/2003/01/geo/wgs84_pos#>\n"
                    + " prefix db-owl: <http://dbpedia.org/ontology/>\n"
                    + "\n"
                    + "SELECT ?artist ?genre ?label ?lat ?long WHERE\n"
                    + "{\n"
                    + "\n"
                    + "    ?artist db-owl:genre ?genre.\n"
                    + "    ?genre geo:location ?location;"
                    + "      rdfs:label ?label.\n"
                    + "    ?location geo:lat ?lat; geo:long ?long.\n"
                    + "{\n"
                    + "    SELECT distinct ?artist  {\n"
                    + "   	 ?artist rdfs:label ?nomArtiste.\n"
                    + "   	 filter regex( ?nomArtiste, \"" + artiste + "\", \"i\")\n"
                    + "    }\n"
                    + "}\n"
                    + "filter (lang(?label) = \"fr\") ."
                    + "}";

            Logger.getLogger(IndexServlet.class.getName()).log(Level.WARNING, query);
            JSONArray jsonarray = new JSONArray();
            JSONObject jsonData = new JSONObject();
            Mappings map = exec.query(query);
            Map<String,String> genres = new HashMap();

            Logger.getLogger(IndexServlet.class.getName()).log(Level.WARNING, "Nombre match " + map.size());
            String artisteURI = "";
            for (Mapping m : map) {
                IDatatype label = (IDatatype) m.getValue("?label");
                IDatatype lon = (IDatatype) m.getValue("?long");
                IDatatype lat = (IDatatype) m.getValue("?lat");
                IDatatype genre = (IDatatype) m.getValue("?genre");
                artisteURI = ((IDatatype) m.getValue("?artist")).getLabel();

                Genre g = new Genre(
                        null == label ? "" : label.getLabel(),
                        null,
                        null == lon ? "" : lon.getLabel(),
                        null == lat ? "" : lat.getLabel()
                );
                genres.put(genre.getLabel(),label.getLabel());
                
                jsonarray.put(g.toJson());
            }
            String JsonFile = context.getRealPath("/Data.json");
            Logger.getLogger(IndexServlet.class.getName()).log(Level.WARNING, context.getRealPath("/Data.json"));
            FileWriter fw = new FileWriter(JsonFile, false);
            BufferedWriter output = new BufferedWriter(fw);
            output.write(jsonarray.toString().replace("\\", ""));
            output.flush();

            request.setAttribute("genres", genres);
            request.setAttribute("artiste", artisteURI );
            request.getRequestDispatcher("artiste.jsp").forward(request, response);
        }
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (EngineException ex) {
            Logger.getLogger(artisteServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (URISyntaxException ex) {
            Logger.getLogger(artisteServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (EngineException ex) {
            Logger.getLogger(artisteServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (URISyntaxException ex) {
            Logger.getLogger(artisteServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
